import Vue from 'vue'
import axios from 'axios'
import router from '@/router'
import store from '@/store'
import qs from 'qs'
import merge from 'lodash/merge'

const http = axios.create({
  timeout: 60000,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json; charset=utf-8',
    //'Content-Type': 'multipart/form-data; charset=utf-8',
  }
})

/**
 * 请求拦截
 */
http.interceptors.request.use(config => {
  mui.showLoading("请求中...","div");
  config.headers['X-Nideshop-Token'] = store.state.user.token;// 请求头带上token
  return config
}, error => {
  mui.hideLoading();
  return Promise.reject(error)
})

/**
 * 响应拦截
 */
http.interceptors.response.use(response => {
  //console.log("response:"+JSON.stringify(response));
  console.log("response:",response);
  if(response.status = 200){
    if (response.data && response.data.errno === 401) { // 401, token失效
      mui.plusReady(function() {
        plus.storage.removeItem('token');
      });
      Vue.cookie.delete('token');
      store.commit('user/updateToken','');
      store.commit('user/updateUserInfo','');
      router.options.isAddDynamicMenuRoutes = false;
      mui.confirm("去登录",'',['取消','确认'],function(e){
        if(e.index==1){
          router.push({ name: 'login' })
        }
      });
    }
    mui.hideLoading();
    return Promise.resolve(response.data);
  } else {
    mui.hideLoading();
    return Promise.reject(response.statusText)
  }
}, error => {
  mui.hideLoading();
  return Promise.reject(error)
})

/**
 * 请求地址处理
 * @param {*} actionName action方法名称
 */
http.adornUrl = (actionName) => {
  // 非生产环境 && 开启代理, 接口前缀统一使用[/proxyApi/]前缀做代理拦截!
  var devUrl = 'http://192.168.0.100:8090/api/';
  //var devUrl = 'http://huizekeji.free.idcfengye.com/api/';
  var proUrl = 'https://yixiaoguoji.qianduyiren.cn/platform-framework/api/';
  return (process.env.NODE_ENV == 'production'  ? proUrl:proUrl) + actionName
}

/**
 * get请求参数处理
 * @param {*} params 参数对象
 * @param {*} openDefultParams 是否开启默认参数?
 */
http.adornParams = (params = {}, openDefultParams = true) => {
  var defaults = {
    't': new Date().getTime()
  };
  return openDefultParams ? merge(defaults, params) : params
}

/**
 * post请求数据处理
 * @param {*} data 数据对象
 * @param {*} openDefultdata 是否开启默认数据?
 * @param {*} contentType 数据格式
 *  json: 'application/json; charset=utf-8'
 *  form: 'application/x-www-form-urlencoded; charset=utf-8'
 */
http.adornData = (data = {}, openDefultdata = true, contentType = 'json') => {
  var defaults = {
    't': new Date().getTime()
  };
  data = openDefultdata ? merge(defaults, data) : data;
  return contentType === 'json' ? JSON.stringify(data) : qs.stringify(data)
}

export default http
